const Koa = require('koa');
const Router = require('koa-router');
const onerror=require('koa-onerror');
const logger=require('koa-logger');
const json=require('koa-json');
const bodyparser = require('koa-bodyparser')
const router=require('./routers/index.js')
const logUtil=require('./utils/log_util.js');
const path = require ('path');
const uuid = require ('uuid');


const app = new Koa();
// const router = new Router();
onerror(app);

app.use(json())//将json转换成对象输出
app.use(logger())
app.use(require('koa-static')(path.join(__dirname+'/public')))
// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}))

//logger自定义
app.use(async (ctx,next)=>{
  //响应开始时间
    const start = new Date();
    //响应间隔时间
    let ms;
    try {
      //开始进入到下一个中间件
      await next();

      ms = new Date() - start;
      //记录响应日志
      logUtil.logResponse(ctx, ms);

    } catch (error) {

      ms = new Date() - start;
      //记录异常日志
      logUtil.logError(ctx, error, ms);
    }

})


app.use(router.routes(),router.allowedMethods());
app.on('error',(err,ctx)=>{
  console.log('server error',err,ctx)
})
// app.listen(3000,()=>{
//       console.log('starting at port 3000');
//   });

//测试生成唯一id模块uuid
console.log(uuid.v1())
module.exports=app;
